package com.hustzp.com.xichuangzhu.poetry;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.XCZBaseFragmentActivity;
import com.hustzp.com.xichuangzhu.login.LoginActivity;
import com.hustzp.com.xichuangzhu.poetry.adapter.CommentListAdapter;
import com.hustzp.com.xichuangzhu.poetry.model.LikePost;
import com.hustzp.com.xichuangzhu.poetry.model.PostComment;
import com.hustzp.com.xichuangzhu.utils.CommonUtils;
import com.hustzp.com.xichuangzhu.utils.Constant;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Copyright (C) 2015 The huimai mobile client Project
 * All right reserved.
 *
 * @author: wuzhimin@huimai365.com
 * @date: 2016/5/31 11:37
 * @Description:一日一赏评论列表
 */
public class CommentListAct extends XCZBaseFragmentActivity {

    private ListView lvCommentList;
    private List<PostComment> comments = new ArrayList<>();
    private CommentListAdapter commentListAdapter;
    private PtrFrameLayout mPtrFrameLayout;
    private LoadMoreListViewContainer loadMoreListViewContainer;
    private int page = 1;
    private int pageCount = 15;

    private LikePost mLikePost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment_list);

        initToolbar();
        initViews();
        initListeners();
    }

    private void initToolbar() {
        TextView navTxt = (TextView) findViewById(R.id.tv_nav_txt);
        navTxt.setText("一日一赏");

        TextView titleTxt = (TextView) findViewById(R.id.tv_title_txt);
        titleTxt.setText("评论");

        ImageButton actionTxt = (ImageButton) findViewById(R.id.btn_write_comment);
        actionTxt.setVisibility(View.VISIBLE);
        actionTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AVUser.getCurrentUser() == null) {
                    startActivity(new Intent(CommentListAct.this, LoginActivity.class));
                    return;
                }

                Intent intent = new Intent(CommentListAct.this, PostCommentActivity.class);
                intent.putExtra(LikePost.class.getSimpleName(), mLikePost);
                startActivityForResult(intent, Constant.REQ_CODE_POST_COMMENT);
            }
        });
    }

    private void initViews() {
        mLikePost = getIntent().getParcelableExtra(LikePost.class.getSimpleName());

        lvCommentList = (ListView) findViewById(R.id.lvCommentList);
        mPtrFrameLayout = (PtrFrameLayout) findViewById(R.id.load_more_list_view_ptr_frame);

        mPtrFrameLayout.setLoadingMinTime(1000);
        mPtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

                // here check list view, not content.
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvCommentList, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                loadPostComment();
            }
        });

        commentListAdapter = new CommentListAdapter(this, comments);
        lvCommentList.setAdapter(commentListAdapter);

        // load more container
        loadMoreListViewContainer = (LoadMoreListViewContainer) findViewById(R.id.load_more_list_view_container);
        loadMoreListViewContainer.useDefaultHeader();
        loadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                //加载更多操作
                loadPostCommentMore();
            }
        });
        loadPostComment();
    }

    private void showMenu(final PostComment postCmt) {
        List<String> menus = new ArrayList<>();
        menus.add("回复");
        menus.add("复制");
        menus.add("举报");

        initSharePopupWindow();
        showSharePopupWindow(menus, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
                switch (i) {
                    case 0:
                        // 回复评论
                        Intent intent = new Intent(CommentListAct.this, PostCommentActivity.class);
                        intent.putExtra(LikePost.class.getSimpleName(), mLikePost);
                        intent.putExtra(PostComment.class.getSimpleName(), postCmt);
                        startActivityForResult(intent, Constant.REQ_CODE_REPLY_COMMENT);
                        break;
                    case 1:
                        // 复制评论
                        CommonUtils.copyToClipboard(CommentListAct.this, postCmt.getCONTENT());
                        showToastInfo("复制成功");
                        break;
                    case 2:
                        // 举报
                        AVObject rptCmtObj = new AVObject("ReportPostComment");
                        if (AVUser.getCurrentUser() != null) {
                            rptCmtObj.put("user", AVUser.getCurrentUser());
                        }
                        rptCmtObj.put("comment", postCmt.getCONTENT());
                        rptCmtObj.saveInBackground(new SaveCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    showToastInfo("举报成功");
                                } else {
                                    showToastInfo("举报失败，请重试");
                                }
                            }
                        });
                        break;
                }
                hideAlert();
            }
        });
    }

    private void initListeners() {
        commentListAdapter.setOnCommentEventListener(new CommentListAdapter.OnCommentEventListener() {
            @Override
            public void onMenu(PostComment postComment) {
                showMenu(postComment);
            }

            @Override
            public void onTop(final PostComment postComment) {
                if (AVUser.getCurrentUser() == null) {
                    startActivity(new Intent(CommentListAct.this, LoginActivity.class));
                    return;
                    //跳转登录
                }
                AVObject user = AVObject.createWithoutData("objectId", AVUser.getCurrentUser().getObjectId());
                AVObject comment = AVObject.createWithoutData("objectId", postComment.getObjectId());
                AVQuery<AVObject> query1 = new AVQuery<>("UpvotePostComment");
                query1.whereEqualTo("user", user);

                AVQuery<AVObject> query2 = new AVQuery<>("UpvotePostComment");
                query2.whereEqualTo("comment", comment);

                AVQuery<AVObject> query = AVQuery.and(Arrays.asList(query1, query2));

                query.findInBackground(new FindCallback<AVObject>() {
                    @Override
                    public void done(List<AVObject> list, AVException e) {
                        if (list != null && !list.isEmpty()) {
                            AVObject object = list.get(0);
                            object.deleteInBackground(new DeleteCallback() {
                                @Override
                                public void done(AVException e) {
                                    postComment.setUpvotescount(postComment.getUPVOTESCOUNT() - 1);
                                    postComment.setTop(false);
                                    commentListAdapter.notifyDataSetChanged();
                                }
                            });
                        } else {
                            AVObject todo = new AVObject("UpvotePostComment");
                            todo.put("user", AVUser.getCurrentUser());
                            todo.put("comment", postComment);
                            todo.saveInBackground(new SaveCallback() {
                                @Override
                                public void done(AVException e) {
                                    if (e == null) {
                                        // 收藏成功
                                        postComment.setUpvotescount(postComment.getUPVOTESCOUNT() + 1);
                                        postComment.setTop(true);
                                        commentListAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    }
                });
            }

        });
        lvCommentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                PostComment postCmt = comments.get(position);
                showMenu(postCmt);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null)
            super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == Constant.REQ_CODE_POST_COMMENT || resultCode == Constant.REQ_CODE_REPLY_COMMENT) && resultCode == RESULT_OK) {
            mPtrFrameLayout.autoRefresh();
        }
    }

    private void loadPostComment() {
        page = 1;
        loadPosts(page, pageCount);
    }

    private void loadPostCommentMore() {
        page++;
        loadPosts(page, pageCount);
    }

    public void loadPosts(int pageIndex, int pageCount) {
        LikePost likePost = (LikePost) getIntent().getParcelableExtra(LikePost.class.getSimpleName());
        AVObject post = AVObject.createWithoutData("objectId", likePost.getObjectId());
        AVQuery<PostComment> query = AVQuery.getQuery(PostComment.class);
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.limit(pageCount);
        query.skip((pageIndex - 1) * pageCount);
        query.whereEqualTo("post", post);
        query.whereEqualTo("hide", false);
        query.include("user");
        query.include("targetUser");
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback<PostComment>() {
            @Override
            public void done(List<PostComment> list, AVException e) {
                if (list != null && !list.isEmpty()) {
                    if (page == 1) {
                        mPtrFrameLayout.refreshComplete();
                        comments.clear();
                    }
                    if (AVUser.getCurrentUser() != null) {
                        for (final PostComment postComment : list) {
                            AVObject user = AVObject.createWithoutData("objectId", AVUser.getCurrentUser().getObjectId());
                            AVObject comment = AVObject.createWithoutData("objectId", postComment.getObjectId());
                            AVQuery<AVObject> query1 = new AVQuery<>("UpvotePostComment");
                            query1.whereEqualTo("user", user);

                            AVQuery<AVObject> query2 = new AVQuery<>("UpvotePostComment");
                            query2.whereEqualTo("comment", comment);
                            AVQuery<AVObject> query = AVQuery.and(Arrays.asList(query1, query2));
                            query.findInBackground(new FindCallback<AVObject>() {
                                @Override
                                public void done(List<AVObject> results, AVException e) {
                                    if (results != null && !results.isEmpty()) {
                                        postComment.setTop(true);
                                        commentListAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    }
                    comments.addAll(list);
                    commentListAdapter.notifyDataSetChanged();
                    loadMoreListViewContainer.loadMoreFinish(false, true);
                } else {
                    page--;
                    loadMoreListViewContainer.loadMoreFinish(false, false);
                }
            }
        });
    }

    public void onClose(View v) {
        finish();
    }
}
